package com.dl698.axdr;

import com.dl698.asn1.axdr.AxdrType;
import com.dl698.util.ReverseByteArrayInputStream;
import com.dl698.util.ReverseByteArrayOutputStream;

/**
 * SIDMAC类
 * 实现安全标识符和媒体访问控制地址的编解码
 * 
 * @author wind
 * @version 1.1.1
 */
public class SIDMAC implements AxdrType {

    private byte[] dataCode = null;
    private SID sid = null;
    private MAC mac = null;

    /**
     * 默认构造函数
     */
    public SIDMAC() {
    }

    /**
     * 设置数据编码
     * 
     * @param dataCode 数据编码
     */
    public void setDataCode(byte[] dataCode) {
        this.dataCode = dataCode;
    }

    /**
     * 设置所有参数
     * 
     * @param sid 安全标识符
     * @param mac 媒体访问控制地址
     */
    public void setAll(SID sid, MAC mac) {
        this.sid = sid;
        this.mac = mac;
    }

    /**
     * 设置安全标识符
     * 
     * @param sid 安全标识符
     */
    public void setSID(SID sid) {
        this.sid = sid;
    }

    /**
     * 设置媒体访问控制地址
     * 
     * @param mac 媒体访问控制地址
     */
    public void setMAC(MAC mac) {
        this.mac = mac;
    }

    @Override
    public int decode(ReverseByteArrayInputStream input) {
        int codeLength = 0;

        sid = new SID();
        codeLength += sid.decode(input);

        mac = new MAC();
        codeLength += mac.decode(input);

        return codeLength;
    }

    @Override
    public int encode(ReverseByteArrayOutputStream output) {
        int codeLength;

        if (dataCode != null) {
            codeLength = dataCode.length;
            for (int i = dataCode.length - 1; i >= 0; i--) {
                try {
                    output.write(dataCode[i]);
                } catch (java.io.IOException e) {
                    throw new RuntimeException(e);
                }
            }
        } else {
            if (sid != null && mac != null) {
                codeLength = 0;
                codeLength += mac.encode(output);
                codeLength += sid.encode(output);
            } else {
                throw new RuntimeException("sid || mac is null");
            }
        }
        return codeLength;
    }

    /**
     * 编码并保存
     * 
     * @param encodingSizeGuess 编码大小预估
     */
    public void encodeAndSave(int encodingSizeGuess) {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        try {
            encode(revOStream);
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException("Error encoding SIDMAC", e);
        }
        this.dataCode = revOStream.getArray();
    }

    @Override
    public String toString() {
        if (sid != null && mac != null) {
            return "sequence: {" + "sid: " + sid + ", mac: " + mac + "}";
        } else {
            return "sid || mac is null";
        }
    }

    // Getter methods
    public SID getSid() {
        return sid;
    }

    public MAC getMac() {
        return mac;
    }
}